package com.huika.dealontop.control.pay.utils;


import android.app.Activity;
import android.content.Intent;
import android.os.Handler;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.pay.activity.PaySuccessActivity;
import com.huika.dealontop.support.domain.OmisePayResultBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.DebugTool;
import com.huika.dealontop.utils.SelectLanguageUtils;
import com.huika.huikalib.utils.MoneyShowTool;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

import org.json.JSONException;

import java.math.BigDecimal;


/**
 * Description:payPal支付
 * Created by zhouweiyong on 2015/11/23.
 */
public class PayPalPay extends BasePay {

    private BaseAct activity;
    private static String payOrder;
    public static final int REQUEST_CODE_PAYMENT = 1;
//    public static final int PAY_SUCCESS = 2;
//    public static final int PAY_FAILURE = 3;
    private static final String CONFIG_CLIENT_ID_SAND_BOX = "ATvqb8aogEcCO4YyoHcDcw9SicfqQs8__aqyas7z1KZCatrzEniSyyuIBm1kP16F3IdxMTd6RLltk9Oo";
    private static final String CONFIG_CLIENT_ID__LIVE = "AZNgeDtvnca1SW3GxQ7anylaqGLDapWCmqRitAIiDYl3L-snZ3FoFp680C8EM940z8ZVHsa9IDXMQCsZ";

    private PayPalConfiguration config = null;

    public static Handler handler;
    private static double money;

    public PayPalPay(BaseAct activity) {
        this.activity = activity;
    }

    public PayPalPay(BaseAct activity, Handler handler) {
        this.handler = handler;
        this.activity = activity;
    }

    private String currency = Constants.CURRENCY;//泰铢

    public void setPayPalOrder(String payOrder) {
        this.payOrder = payOrder;
    }

    private void getConfig() {
        if (UrlConstants.isReleaseEnvironment()) {
            config = new PayPalConfiguration()
                    .environment(PayPalConfiguration.ENVIRONMENT_PRODUCTION)
                    .languageOrLocale(SelectLanguageUtils.getCurrentLanguage(activity))
                    .clientId(CONFIG_CLIENT_ID__LIVE);
        } else {
            config = new PayPalConfiguration()
                    .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
                    .languageOrLocale(SelectLanguageUtils.getCurrentLanguage(activity))
                    .clientId(CONFIG_CLIENT_ID_SAND_BOX);
        }
    }

    /**
     * @description：使用支付的activity中需要调用启动服务
     * @author zc
     * @date 2015年8月6日 下午3:40:47
     */
    public void startServer() {
        Intent intent = new Intent(activity, PayPalService.class);
        getConfig();
//		config.languageOrLocale(LanguageUtils.getCurrentLanguage());
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        activity.startService(intent);
    }

    /**
     * @description：设置当前货币种类，默认：泰铢
     * @author zc
     * @date 2015年8月11日 下午2:59:43
     */
    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public void receiveResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm =
                        data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        DebugTool.v("pay response json", confirm.toJSONObject().toString(4));
                        DebugTool.v("pay response json", confirm.getPayment().toJSONObject().toString(4));
//                        System.out.println(confirm.toJSONObject().getJSONObject("response").getString("id"));
                        paymentOrder(activity, activity.getString(R.string.common_lang), getPayOrderNo(), confirm.toJSONObject().getJSONObject("response").getString("id"), getTotalMoney(), handler);
                        /**
                         *  TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
                         * or consent completion.
                         * See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                         * for more details.
                         *
                         * For sample mobile backend interactions, see
                         * https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
                         */
//                        Toast.makeText(
//                                activity,
//                                "PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
//                                .show();

                    } catch (JSONException e) {
                        e.printStackTrace();
                        DebugTool.v("pay result", "an extremely unlikely failure occurred: ");
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                DebugTool.v("pay result", "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
//            	ToastMsg.showToastMsg(activity, "支付失败");
                handler.sendEmptyMessage(BasePay.PAY_FAILURE);
                DebugTool.v(
                        "pay result",
                        "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        }
    }

    /**
     * @description：PayPal支付判断是否支付成功
     * @author zc
     * @date 2015年8月20日 上午10:49:28
     */
    private void paymentOrder(final BaseAct act, String lang, final String paymentOrderId, String outOrderId, double realAmount, final Handler handler) {
        act.showLoadingDialog("");
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userId", getUserId());
        ajaxParams.putCommonTypeParam("payChannel", "2");
        ajaxParams.putCommonTypeParam("lang", lang);
        ajaxParams.putCommonTypeParam("paymentOrderId", paymentOrderId);
        ajaxParams.putCommonTypeParam("outOrderId", outOrderId);
        ajaxParams.putCommonTypeParam("realAmount", MoneyShowTool.twolastDF(realAmount));
        FormResultRequest<OmisePayResultBean> request = new FormResultRequest<OmisePayResultBean>(UrlConstants.PAYMENTSUCCESS, new Response.Listener<RequestResult<OmisePayResultBean>>() {
            @Override
            public void onResponse(RequestResult<OmisePayResultBean> arg0) {
                act.dismissLoadingDialog();
                //handler.sendEmptyMessage(BasePay.PAY_SUCCESS);
                Intent intent = new Intent(activity, PaySuccessActivity.class);
                intent.putExtra(Constants.PAY_ORDERID,getOrderNo());
                intent.putExtra(Constants.OMISE_PAY_RESULT,arg0.getRs());
                intent.putExtra(Constants.PAY_PAYMENTORDERID,paymentOrderId);
                intent.putExtra(BasePay.PHONE, getPhone());
                activity.showActivity(activity, intent);
                activity.finish();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                act.dismissLoadingDialog();
                handler.sendEmptyMessage(BasePay.PAY_FAILURE);
            }
        },
                new TypeToken<RequestResult<OmisePayResultBean>>() {
                }.getType());
        request.setRequestParams(ajaxParams);
        act.executeRequest(request);
    }

    /**
     * @description：在需要支付的activity中退出时调用此方法
     * @author zc
     * @date 2015年8月6日 下午3:43:50
     */
    public void stopServer() {
        activity.stopService(new Intent(activity, PayPalService.class));
    }

    /**
     * @description：钱 和货币号  如 USD  RMB  THB
     * @author zc
     * @date 2015年8月7日 上午11:21:46
     */
    public void paypalPay(double money, String currency) {
        this.money = money;
        PayPalPayment payment = new PayPalPayment(new BigDecimal(MoneyShowTool.twolastDF(money)), currency, String.valueOf(getPayOrderNo()),
                PayPalPayment.PAYMENT_INTENT_SALE);
        payment.invoiceNumber(getPayOrderNo());
        payment.custom(getPayOrderNo());
        Intent intent = new Intent(activity, PaymentActivity.class);
        // send the same configuration for restart resiliency
//		config.languageOrLocale(LanguageUtils.getCurrentLanguage());
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
        activity.startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    @Override
    public void pay() {
        paypalPay(getTotalMoney(), currency);
    }
}
